package com.ding.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 买票的例子
 *
 * 真正的多线程开发,公司中的开发
 * 线程就是一个单独的资源类,没有任何附属的操作
 * 1. 属性、方法
 *
 * @author ding
 * @date 2021/7/17 18:05
 */


public class SaleTicketDemo02 {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "B").start();

    }
}

/**
 * Lock三部曲
 * 1. new ReenTrantLock
 * 2. lock.lock
 * 3. finally lock.unlock
 */
class Ticket2 {
    //属性.方法
    private int number = 50;
    //买票的方式
    Lock lock = new ReentrantLock();
    public  void sale() {
        lock.lock();
        try {
            if (number > 0) {
                String name = Thread.currentThread().getName();
                System.out.println(name + "卖出了" + (number--) + "票，剩余：" + number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}